from app.database.postgre import SessionDep, select, col
from app.database.models import Account, App, CardType
from app.models import responses
from app.models.common import CardTypeIdJson, CardTypeIdParams, AppIdParams
from app.models.card_types import AppCardTypesListParams, CreateCardTypeJson, UpdateCardTypeJson


async def get_card_types_list(account: Account,
                              query_params: AppCardTypesListParams,
                              session: SessionDep, ):
    # 构建查询参数
    page = query_params.page
    page_size = query_params.page_size

    # 获取查询的应用
    app = session.get(App, query_params.app_id)
    if not app or app.account_id != account.aid:
        return responses.Response303()

    # 构建查询语句
    query = session.query(CardType).filter(CardType.app_id == app.id).order_by(col(CardType.id).asc())

    # 获取总数
    total_count = query.count()
    total_pages = (total_count + page_size - 1) // page_size

    # 获取分页数据
    offset = (page - 1) * page_size
    paginated_query = query.offset(offset).limit(page_size)
    paginated_card_types = paginated_query.all()

    return responses.SuccessResponse(
        data={
            'total': total_count,
            'total_pages': total_pages,
            'page': page,
            'page_size': len(paginated_card_types),
            'list': [card_type.model_dump() for card_type in paginated_card_types]
        }
    )


async def create_new_card_type(account: Account,
                               json_data: CreateCardTypeJson,
                               session: SessionDep):
    # 查询应用是否存在
    app = session.get(App, json_data.app_id)
    if not app or app.account_id != account.aid:
        return responses.Response303()

    # 检查应用是否被超管禁用
    if app.force_disabled:
        return responses.Response304()

    # 构建创建卡种的参数
    card_type_data = json_data.model_dump(exclude_none=True)

    # 提交新卡种
    new_card_type = CardType(**card_type_data)
    try:
        session.add(new_card_type)
        session.commit()
    except Exception as e:
        session.rollback()
        raise e

    session.refresh(new_card_type)

    return responses.SuccessResponse(msg='卡种创建成功', data=new_card_type.model_dump())


async def delete_card_type(account: Account,
                           json_data: CardTypeIdJson,
                           session: SessionDep):
    # 获取对应的应用
    app = session.get(App, json_data.app_id)
    if not app or app.account_id != account.aid:
        return responses.Response303()

    # 检查应用是否被超管禁用
    if app.force_disabled:
        return responses.Response304()

    # 获取被删除的卡种
    card_type = session.exec(
        select(CardType).where(CardType.id == json_data.card_type_id, CardType.app_id == app.id)).first()
    if not card_type:
        return responses.Response403()

    session.delete(card_type)
    session.commit()

    return responses.SuccessResponse(msg='卡种已删除', data=card_type.model_dump(include={'id'}))


async def get_card_type_info(account: Account,
                             query_params: CardTypeIdParams,
                             session: SessionDep):
    # 获取对应的应用
    app = session.get(App, query_params.app_id)
    if not app or app.account_id != account.aid:
        return responses.Response303()

    # 获取查询的卡种
    card_type_id = query_params.card_type_id
    operate_card_type = session.exec(
        select(CardType).where(CardType.id == card_type_id, CardType.app_id == app.id)).first()
    if not operate_card_type:
        return responses.Response403()

    return responses.SuccessResponse(data=operate_card_type.model_dump())


async def update_card_type(account: Account,
                           json_data: UpdateCardTypeJson,
                           session: SessionDep):
    # 获取对应的应用
    app = session.get(App, json_data.app_id)
    if not app or app.account_id != account.aid:
        return responses.Response303()

    # 检查应用是否被超管禁用
    if app.force_disabled:
        return responses.Response304()

    # 构建更新卡种的参数
    card_type_id = json_data.card_type_id
    other_data = json_data.model_dump(exclude={'app_id', 'card_type_id'}, exclude_none=True)

    # 获取对应的卡种
    operate_card_type = session.exec(
        select(CardType).where(CardType.id == card_type_id, CardType.app_id == app.id)).first()
    if not operate_card_type:
        return responses.Response403()

    CardType.sqlmodel_update(operate_card_type, other_data)
    session.commit()
    session.refresh(operate_card_type)

    return responses.SuccessResponse(msg='卡种更新成功', data=operate_card_type.model_dump())


async def get_simple_card_types(account: Account, query_params: AppIdParams, session: SessionDep):
    """获取应用卡种列表的简要"""
    app = session.get(App, query_params.app_id)
    if not app or app.account_id != account.aid:
        return responses.Response303()

    stmt = (select(CardType.id, CardType.name)
            .where(CardType.app_id == app.id)
            .order_by(col(CardType.create_time).asc(), col(CardType.id).asc()))

    result = session.exec(stmt)

    simple_card_types = [
        {"id": card_type.id, "name": card_type.name}
        for card_type in result.all()
    ]

    return responses.SuccessResponse(data={
        'card_types': simple_card_types
    })
